<?php

/**
 * Class for logs rotate.
 *
 * 
 *
 * @package lib.model
 */ 
class LogRotate
{

    public static function rotate()
    {
        SymConfig::set('Logrotate start', date('Y.m.d H:i:s'));
        //check logging enabled
        if( sfConfig::get('sf_logging_enabled') == false)
        {
            return false;
        }
        
        if( sfConfig::get('sf_logging_rotate') == false )
        {
            return false;
        }
        
        $history = sfConfig::get('sf_logging_history', 10);
        $logDir = sfConfig::get('sf_log_dir');
        
        $minsize = sfConfig::get('sf_logging_minsize_kb', 1000) * 1024;
        
        // counter for renamed array
        $k = 0;
        
        // get all logs files names from log directory 
        $arLogDir = glob($logDir . '/*.log*');
        
        // array with unique file names
        $arFileUname = array();
        
        //create array for rename
        for( $i = 0; $i < count($arLogDir); $i++ )
        {
            $arFile = explode('.log', $arLogDir[$i]);
            
            // remove '.' from version number
            $arFile[1] = str_replace('.', '', $arFile[1]);   
            
            // file without version 
            if( !$arFile[1] )
            {
                //if file size less minsize from logging.yml,
                // he is not rotated 
                if( filesize($arLogDir[$i]) > $minsize )
                {
                    $arFileUname[] = $arFile[0];
                }
            }
            
            $arFileRenamed[$k]['name'] = $arFile[0];
            $arFileRenamed[$k]['oldVersion'] = $arFile[1];
            $arFileRenamed[$k]['newVersion'] = $arFile[1] + 1;
            $arFileRenamed[$k]['oldName'] = $arFile[0] . '.log' . (($arFile[1]) ? '.' . $arFile[1] : '');
            $arFileRenamed[$k]['newName'] = $arFile[0] . '.log' . '.' . ($arFile[1] + 1);
            
            // array with file name
            //$arFileUnames[] = $arFileRenamed[$k]['name']; 
            
            $k++;
        }
        //debugvar($arFileRenamed, 'arFileRenamed');
        sort($arFileRenamed);
        
        foreach( $arFileUname as $fileUname )
        {
            for( $j = (count($arFileRenamed) - 1); $j >= 0; $j-- )
            {
                if( $arFileRenamed[$j]['name'] == $fileUname )
                {
                    if( $arFileRenamed[$j]['oldVersion'] >= $history )
                    {
                        unlink($arFileRenamed[$j]['oldName']);
                    }
                    else
                    {
                        rename($arFileRenamed[$j]['oldName'], $arFileRenamed[$j]['newName']);
                    }
                }
            }
        }

    }
}
